package cd.cdyb.sms.service.impl;

import cd.cdyb.sms.dto.MessageResponse;
import cd.cdyb.sms.service.RedisService;
import cd.cdyb.sms.service.SmsService;
import cd.cdyb.sms.utils.CacheUtils;
import cd.cdyb.sms.utils.JacksonUtilPlus;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: lilin
 * @CreateTime: 2024-05-16  11:36
 * @Description: 短信
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Resource
    private RestTemplate restTemplate;

    @Value("${sms.url}")
    private String url;

    @Value("${sms.appid}")
    private String appid;

    @Value("${sms.appKey}")
    private String appKey;

    @Value("${sms.new_url}")
    private String newUrl;

    @Value("${sms.new_appid}")
    private String newAppid;

    @Value("${sms.new_appKey}")
    private String newAppKey;

    @Resource
    private RedisService redisService;

    @Override
    public Map<String, String> sendMessage(String phone, String templateId, String content, Integer type, String msgId) {
        Map<String, String> result = new HashMap<>();
        try {
            String uri = null;
            if (5 == type) {
                uri = newUrl + "/send/submitBatchCustomMarketingMsgId";
            } else if (6 == type) {
                uri = newUrl + "/send/submitBatchCustomBusinessMsgId";
            } else {
                log.info("短信发送失败，原因：未知短信类型");
                result.put("isSucess", "false");
                return result;
            }
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            Map<String, Object> requestParams = new HashMap<>();
            requestParams.put("appid", newAppid);
            requestParams.put("appkey", newAppKey);
            requestParams.put("template_id", templateId);
            requestParams.put("msg_id", msgId);
            if (StringUtils.isNotBlank(content)) {
                requestParams.put("connect", content + ":" + phone);
            } else {
                requestParams.put("connect", phone);
            }
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestParams, headers);
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(uri, requestEntity, JSONObject.class);
            JSONObject body = responseEntity.getBody();
            if (responseEntity.getStatusCode() != HttpStatus.OK || Objects.isNull(body)) {
                log.info("短信发送失败，原因：第三方请求失败");
                result.put("isSucess", "false");
            }
            String code = body.getString("code");
            if ("200".equals(code)) {
                result.put("isSucess", "true");
                String task_no = body.getString("task_no");
                result.put("no", task_no);
                return result;
            } else {
                String param = JSONObject.toJSONString(requestParams);
                log.info("短信发送失败，原因：[{}] , 失败入参[{}]", code, param);
                result.put("isSucess", "false");
                result.put("desc", code);

                return result;
            }
        } catch (Exception e) {
            log.info("短信发送失败，原因:{}", e.getMessage());
        }

        result.put("isSucess", "false");
        return result;
    }

    @Override
    public List<MessageResponse> findNewMessageList() {
        try {
            String uri = "https://sendapi.fulongzy.com/index/send/businessReceive";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            Map<String, Object> requestParams = new HashMap<>();
            requestParams.put("appid", appid);
            requestParams.put("appkey", appKey);
            String key = (String) redisService.vGet(CacheUtils.CacheName.CHECK_KEY, "ALL");
            log.info("redis获取CHECK_KEY[{}]", key);
            if (key != null) {
                requestParams.put("last_check_key", key);
            }
            log.info("发送给第三方的数据[{}]", JacksonUtilPlus.toJSon(requestParams));
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestParams, headers);
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(uri, requestEntity, JSONObject.class);
            JSONObject body = responseEntity.getBody();
            if (responseEntity.getStatusCode() != HttpStatus.OK || Objects.isNull(body)) {
                log.info("短信发送失败，原因：第三方请求失败");
                return new ArrayList<>();
            }
            String code = body.getString("code");
            if ("200".equals(code)) {
                String check_key = body.getString("check_key");
                log.info("实际获取的数据[{}]", body);
                if (StringUtils.isNotBlank(check_key)) {
                    //更新短信平台key
                    redisService.vPut(CacheUtils.CacheName.CHECK_KEY, "ALL", check_key);
                }
                JSONArray data = body.getJSONArray("data");
                List<MessageResponse> messageResponses = data.toJavaList(MessageResponse.class);
                return messageResponses;
            } else {
                log.info("短信发送失败，原因：" + code);
                return new ArrayList<>();
            }
        } catch (Exception e) {
            log.info("短信发送失败，原因:{}", e.getMessage());
            return new ArrayList<>();

        }
    }

    @Override
    public List<MessageResponse> findNewMessageListWithNew() {
        try {
            String uri = newUrl + "/send/internationalReceive";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            Map<String, Object> requestParams = new HashMap<>();
            requestParams.put("appid", newAppid);
            requestParams.put("appkey", newAppKey);
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestParams, headers);
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(uri, requestEntity, JSONObject.class);
            JSONObject body = responseEntity.getBody();
            if (responseEntity.getStatusCode() != HttpStatus.OK || Objects.isNull(body)) {
                log.info("短信发送失败，原因：第三方请求失败");
                return new ArrayList<>();
            }
            String code = body.getString("code");
            if ("200".equals(code)) {
                log.info("实际获取的数据[{}]", body);
                JSONArray data = body.getJSONArray("data");
                List<MessageResponse> messageResponses = data.toJavaList(MessageResponse.class);
                return messageResponses;
            } else {
                log.info("短信发送失败，原因：" + code);
                return new ArrayList<>();
            }
        } catch (Exception e) {
            log.info("短信发送失败，原因:{}", e.getMessage());
            return new ArrayList<>();

        }
    }
}
